//
//  GuideManager.m
//  Guide
//
//  Created by lanou3g on 16/5/13.
//  Copyright © 2016年 liu. All rights reserved.
//

#import "GuideManager.h"

#define kScreen [UIScreen mainScreen].bounds

static NSString *identifer = @"cell";

@interface GuideViewCell : UICollectionViewCell

@property (nonatomic,strong) UIImageView *imgView;
@property (nonatomic,strong) UIButton *button;

@end
@implementation GuideViewCell

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setView];
    }
    return self;
}

- (void)setView {
    self.imgView = [[UIImageView alloc]init];
    self.imgView.frame = kScreen;
    self.center = CGPointMake(kScreen.size.width/2, kScreen.size.height/2);
    [self.contentView addSubview:self.imgView];
    
    
    self.layer.masksToBounds = YES;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.hidden = YES;
    [button setFrame:CGRectMake(0, 20, 220, 50)];
    [button setTitle:@"开始体验" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button.layer setCornerRadius:5];
    [button.layer setBorderColor:[UIColor blackColor].CGColor];
    [button.layer setBorderWidth:1.0f];
    [button setBackgroundColor:[UIColor whiteColor]];
    
    self.button = button;
    
    [self.contentView addSubview:self.button];
    
    [self.button setCenter:CGPointMake(kScreen.size.width / 2, kScreen.size.height - 90)];
}

@end



@interface GuideManager ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>

@property (nonatomic,strong) UIWindow *window;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) NSArray *images;
@property (nonatomic,strong) UIPageControl *pageControl;

@end

@implementation GuideManager

+ (instancetype)shared {
    static GuideManager *manager = nil;
    @synchronized(self) {
        if (!manager) {
            manager = [[GuideManager alloc]init];
        }
    }
    return manager;
    
//    static id __staticObject = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        __staticObject = [GuideManager new];
//    });
//    return __staticObject;
}

- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        
        CGRect screen = [UIScreen mainScreen].bounds;
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        layout.itemSize = screen.size;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _collectionView = [[UICollectionView alloc]initWithFrame:screen collectionViewLayout:layout];
        _collectionView.bounces = NO;
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.pagingEnabled = YES;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        
        /// 注册cell
        [_collectionView registerClass:[GuideViewCell class] forCellWithReuseIdentifier:identifer];
        
    }
    return _collectionView;
}
- (UIPageControl *)pageControl {
    if (_pageControl == nil) {
        
        _pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 0, kScreen.size.width, 44)];
        _pageControl.center = CGPointMake(kScreen.size.width/2, kScreen.size.height - 60);
        
    }
    return _pageControl;
}
- (void)showGuideViewWithImages:(NSArray *)images {
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *version = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleShortVersionString"];
    BOOL show = [ud boolForKey:[NSString stringWithFormat:@"%@",version]];
    if (!show && self.window == nil) {
        self.images = images;
        self.pageControl.numberOfPages = images.count;
        self.window = [UIApplication sharedApplication].keyWindow;
        
        [self.window addSubview:self.collectionView];
        [self.window addSubview:self.pageControl];
        
        [ud setBool:YES forKey:[NSString stringWithFormat:@"%@",version]];
        [ud synchronize];
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.images.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    GuideViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifer forIndexPath:indexPath];
    
    NSString *path = [self.images objectAtIndex:indexPath.row];
    UIImage *img = [UIImage imageWithContentsOfFile:path];
    CGSize size = [self adapterSizeImageSize:img.size compareSize:kScreen.size];
    
    // 自适应图片位置，图片可以是任意尺寸，会自动缩放
    cell.imgView.frame = CGRectMake(0, 0, size.width, size.height);
    cell.imgView.image = [UIImage imageWithContentsOfFile:path];
    cell.imgView.center = CGPointMake(kScreen.size.width / 2, kScreen.size.height / 2);
    
    if (indexPath.row == self.images.count - 1) {
        [cell.button setHidden:NO];
        [cell.button addTarget:self action:@selector(nextButtonHandler:) forControlEvents:UIControlEventTouchUpInside];
    } else {
        [cell.button setHidden:YES];
    }
    
    return cell;
}
- (CGSize)adapterSizeImageSize:(CGSize)imageSize compareSize:(CGSize)compareSize {
    CGFloat width = compareSize.width;
    CGFloat height = compareSize.width / imageSize.width * imageSize.height;
    
    if (height < compareSize.height) {
        width = compareSize.height / height * width;
        height = compareSize.height;
    }
    return CGSizeMake(width, height);
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    self.pageControl.currentPage = scrollView.contentOffset.x / kScreen.size.width;
}
- (void)nextButtonHandler:(UIButton *)sender {
    [self.collectionView removeFromSuperview];
    [self setWindow:nil];
    [self setCollectionView:nil];
}

@end
